package com.example.exceldemo.write;

import com.alibaba.excel.EasyExcel;
import com.example.exceldemo.util.CustomCellWriteWidthConfig;
import com.example.exceldemo.util.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: yanhongwei
 * @Date: 2023/07/13 14:27:23
 * @Description: TODO
 */

@Component
@Slf4j
public class ExcelWriteTool {

    public void exportDictData(HttpServletResponse response, Class<?> clazz, String fileName, List<?> dictData) {
        //设置文件下载的请求头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //调用方法执行写操作
        try {
            EasyExcel.write(response.getOutputStream(), clazz)
                    .sheet(fileName)
                    .registerWriteHandler(new CustomCellWriteWidthConfig()) //自定义列宽
                    .registerWriteHandler(EasyExcelUtils.getStyleStrategy()) //自定义样式
                    .doWrite(dictData);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}